package com.easy.util;

import org.apache.commons.codec.digest.DigestUtils;

public class DigestUtil {

    private static final int SALTINDEX=1;//盐值下标
    private static final int COUNTINDEX=12;//加密次数下标
    private static final char[] ITEMS={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    public static String randomDigest(String pass){
        int randomCountIndex=(int)(Math.random()*ITEMS.length);
        int randomSaltIndex=(int)(Math.random()*ITEMS.length);

        char count=ITEMS[randomCountIndex];//随机获取加密次数
        //System.out.println(count);
        char salt=ITEMS[randomSaltIndex];//随机获取盐值
        //System.out.println(salt);

        String result=pass+salt;

        for (int i=0;i<count;i++){
            //加密
            result=DigestUtils.md5Hex(result);
        }
        //result就是加密后的字符串
        result=result.substring(0,SALTINDEX)+salt+result.substring(SALTINDEX);
        //System.out.println(result);
        result=result.substring(0,COUNTINDEX)+count+result.substring(COUNTINDEX);
        //System.out.println(result);
        return result;
    }

    public static boolean decode(String pass,String digestPass){
        char salt=digestPass.charAt(SALTINDEX);
        char count=digestPass.charAt(COUNTINDEX);
        //开始加密
        String result=pass+salt;
        for (int i=0;i<count;i++){
            result=DigestUtils.md5Hex(result);
        }
        result=result.substring(0,SALTINDEX)+salt+result.substring(SALTINDEX);
        result=result.substring(0,COUNTINDEX)+count+result.substring(COUNTINDEX);
        //System.out.println(result);
        return result.equals(digestPass);
    }

    //测试
    public static void main(String[] args) {
        //randomDigest("123");//7d19fa0124b25eb38f76954a7b929cc77c

        System.out.println(decode("123","7d19fa0124b25eb38f76954a7b929cc77c"));
    }

}
